package com.woate.wingframework.test.junit4;

import com.woate.wingframework.annotations.devtime.TestOrder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 提供排序的单元测Runner
 */
public class OrderedSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner {
    private static final Log logger = LogFactory.getLog(OrderedSpringJUnit4ClassRunner.class.getSimpleName());
    /**
     * 定义一个静态变量，确保 computeTestMethods() 中的排序逻辑只运行一次（JUnit 会调用两次）
     */
    private static List<FrameworkMethod> testMethodList;

    public OrderedSpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected List<FrameworkMethod> computeTestMethods() {
        if (testMethodList == null) {
            // 获取带有 TestOrder 注解的方法
            testMethodList = super.computeTestMethods();
            //进行排序
            sort(testMethodList);
        }
        return testMethodList;
    }

    void sort(List<FrameworkMethod> testMethodList) {
        // 获取测试方法上的 TestOrder 注解，并对所有的测试方法重新排序
        Collections.sort(testMethodList, new Comparator<FrameworkMethod>() {
            @Override
            public int compare(FrameworkMethod m1, FrameworkMethod m2) {
                TestOrder o1 = m1.getAnnotation(TestOrder.class);
                TestOrder o2 = m2.getAnnotation(TestOrder.class);
                if (o1 == null || o2 == null) {
                    return 0;
                }
                return o1.value() - o2.value();
            }
        });
        int sortPos = 0;
        for (FrameworkMethod method : testMethodList) {
            sortPos++;
            logger.info("[" + sortPos + "]-" + method.getName());
        }
    }


}
